package com.wolf.etl.core.loadbalance;

import com.wolf.etl.enumeration.INSTANCE_STATUS;
import com.wolf.etl.model.EtlInstanceModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 平均负载均衡
 *
 * @author sdyang
 * @date 2019/12/5 14:47
 **/
@Service("averageLoadBalance")
public class AverageLoadBalance implements AbstractLoadBalance {

    @Override
    public List<EtlInstanceModel> select(List<EtlInstanceModel> instances, Integer pageNum) {

        if (CollectionUtils.isEmpty(instances)) {
            return new ArrayList<EtlInstanceModel>();
        }

        // 只有一个实例
        if (instances.size() == 1) {
            instances.get(0).setMax_page_num(pageNum);
            return instances;
        }

        int size = instances.size();
        int pageSize = pageNum / size;
        int maxPage = 0;

        // 剔除已分配运行的实例
        for (int i = 0; i < size; i++) {
            if (instances.get(i).getPage_num() != 0
                    || instances.get(i).getStatus() == INSTANCE_STATUS.FINISH.getValue()
                    || instances.get(i).getStatus() == INSTANCE_STATUS.ERROR.getValue()) {
                if (instances.get(i).getMax_page_num() > maxPage) {
                    maxPage = instances.get(i).getMax_page_num();
                }
                instances.remove(i);
                size--;
            }

        }

        // 分配未运行的实例
        for (int i = 0; i < size; i++) {
            instances.get(0).setPage_num(maxPage + 1);

            if (maxPage + pageSize > pageNum) {
                maxPage = pageNum;
            }
            instances.get(0).setMax_page_num(pageNum);
        }

        return instances;
    }


}
